package com.project.frba.bi;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * The FieldHandler for the Date class
 * 
 */
public class TimeQuantityParser {

	public String convertUponGet(Object value) {
		if (value instanceof Integer) {
			Integer t = (Integer) value;
			return days(t) +  hours(t) + minutes(t);

		} else if (value == null) {
			return "";
		} else {
			return value.toString();
		}

	}

	private String minutes(Integer t) {
		if ((t%60) > 0) {
			return new Integer(t%60).toString() + "m ";
		}
		return "";
	}

	private String hours(Integer t) {
		Integer hours = t/60;
		if ((hours%24) > 0) {
			return new Integer(hours%24).toString() + "h ";
		}		
		return "";
	}

	private String days(Integer t) {
		if (t >= 60*24) {
			return new Integer(t/(60*8)).toString() + "d ";
		}
		return "";
	}

	public Long convertUponSet(Object value) {
		String quantity = (String) value;		
		/*
		 * \\ significa solo \, se usan 2 porque hay que escaparla en java.
		 * [\\s]* matchea con n espacios en blanco
		 * (\\d+d) 1 o más digitos y la letra d
		 * (\\d+h) 1 o más digitos y la letra h
		 * (\\d+m) 1 o más digitos y la letra m 
		 */
		Matcher matcher = Pattern.compile("[\\s]*(\\d+d)?[\\s]*(\\d+h)?[\\s]*(\\d+m)?[\\s]*").matcher(quantity);		
		int total = 0;		
		
		if (matcher.matches()) {
			for (int i=1; i <= matcher.groupCount(); i++) {
				String s = matcher.group(i);
				if (s != null) {
					char c = (s.charAt(s.length()-1));
					switch (c) {
						case 'd': total += 60*24*Integer.parseInt(s.substring(0, s.length()-1)); break;
						case 'h': total += 60*Integer.parseInt(s.substring(0, s.length()-1)); break;
						case 'm': total += Integer.parseInt(s.substring(0, s.length()-1)); break;
					}
				}				
			}
		}

		return new Long(total);
	}

}
